package com.github.icloudpay.pay.core.service.pay.wechat.service;

import java.math.BigDecimal;
import java.util.Map;

import org.apache.commons.lang.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.icloudpay.pay.core.biz.PayChannelConfigBiz;
import com.github.icloudpay.pay.core.biz.PayOrderBiz;
import com.github.icloudpay.pay.core.biz.PaySerialBiz;
import com.github.icloudpay.pay.core.entity.PayChannelConfig;
import com.github.icloudpay.pay.core.entity.PayOrder;
import com.github.icloudpay.pay.core.entity.PaySerial;
import com.github.icloudpay.pay.core.service.pay.PayCallbackService;
import com.github.wxiaoqi.security.common.admin.pay.request.CallbackRequest;
import com.github.wxiaoqi.security.common.admin.pay.response.WechatCallbackReponse;
import com.github.wxiaoqi.security.common.util.Utils;

/**
 * 微信支付回调
 * @author hexufeng
 *
 */
@Service("wechatPayCallBackService")
public class WechatPayCallBackService {
	
	private static final Logger logger = (Logger) LoggerFactory.getLogger(WechatPayCallBackService.class);
	
	@Autowired
	private PaySerialBiz paySerialBiz;
	@Autowired
	private PayOrderBiz payOrderBiz;
	@Autowired
	private PayChannelConfigBiz payChannelConfigBiz;
	@Autowired
	private WechatSignatureService wechatSignatureService;
	@Autowired
	private PayCallbackService payCallbackService;
	
	public WechatCallbackReponse payCallBack(Map<String, Object> request){
		
		WechatCallbackReponse callbackReponse = new WechatCallbackReponse();
		
		String out_trade_no = (String) request.get("out_trade_no");
		PaySerial paySerial = new PaySerial();
		paySerial.setSerialNo(out_trade_no);
		PaySerial selectPaySerial = paySerialBiz.selectOne(paySerial);
	    if(selectPaySerial == null){
            logger.error("查询支付流水为空, out_trade_no{}",out_trade_no);
            callbackReponse.setReturn_code("FAIL");
			return callbackReponse;
        }
	    
	    PayOrder payOrder = new PayOrder();
		payOrder.setPayOrderNo(selectPaySerial.getPayOrderNo());
		payOrder.setPlatformId(selectPaySerial.getPlatformId());
		PayOrder selectPayOrder = payOrderBiz.selectOne(payOrder);
	    
		PayChannelConfig payChannelConfig = new PayChannelConfig();
		payChannelConfig.setMerId(selectPayOrder.getMerId());
		payChannelConfig.setPlatformId(selectPayOrder.getPlatformId());
		payChannelConfig.setPayChannelNo(selectPaySerial.getPayChannelNo());
		payChannelConfig.setPayCompanyNo(selectPaySerial.getPayCompanyNo());
		PayChannelConfig channelConfig = payChannelConfigBiz.getPayChannelConfig(payChannelConfig);
		request.remove("TransCode");
		request.remove("$sessionClass");
		request.remove("serviceCode");
        logger.debug("微信APP支付回调 ： requestParams is{}",request);
        
        String total_fee = Utils.changeToYuan(ObjectUtils.toString(request.get("total_fee")));
        String trade_no = (String) request.get("transaction_id");
        
        CallbackRequest callbackRequest = new CallbackRequest();
        callbackRequest.setRequestNo(out_trade_no);
        callbackRequest.setOrderAmt(new BigDecimal(total_fee));
        callbackRequest.setRemoteTxJournalNo(trade_no);
       
        
        String sign = (String) request.get("sign");
        if(wechatSignatureService.vailSign(request,sign,channelConfig)){
        	logger.info("微信支付回调验签成功trade_no:{},out_trade_no:{}",trade_no,out_trade_no);
        	
        	if("SUCCESS".equals(request.get("result_code"))){
        		//验证成功
        		callbackRequest.setStatus("00");
        		payCallbackService.callBack(callbackRequest);
        	}else {
                logger.info("微信支付回调状态{},不做处理",request.get("result_code"));
                callbackRequest.setStatus("01");
                payCallbackService.callBack(callbackRequest);
            }
        	callbackReponse.setReturn_code("SUCCESS");
        }else{
        	logger.info("微信支付回调验签失败");
            callbackReponse.setReturn_code("FAIL");
            callbackReponse.setReturn_msg("签名失败");
        }
        return callbackReponse;
	}

}
